const express = require('express');
const router = express.Router();
const pool = require('../db');
const authMiddleware = require('../middleware/auth');
const { createLog } = require('../log');

// GET /api/hospitals
// If page & limit provided returns { hospitals: [...], total }
// Otherwise returns { hospitals: [...] } (all)
router.get('/hospitals', authMiddleware, async (req, res) => {
  try {
    // log page open (non-blocking)
    createLog(req, { message: '打开医院列表', tp: 'view' });

    const page = req.query.page ? Math.max(1, parseInt(req.query.page, 10) || 1) : null;
    const limit = req.query.limit ? Math.max(1, parseInt(req.query.limit, 10) || 10) : null;
    const offset = page && limit ? (page - 1) * limit : null;

    // allow sorting by safe fields
    const allowedSorts = {
      hos_name: 'h.hos_name',
      hos_code: 'h.hos_code',
      county_name: 'c.county_name',
      id: 'h.id'
    };
    const sortBy = typeof req.query.sort_by === 'string' ? req.query.sort_by : null;
    let sortOrder = typeof req.query.sort_order === 'string' ? req.query.sort_order.toLowerCase() : null;
    if (sortOrder !== 'asc' && sortOrder !== 'desc') sortOrder = null;

    let orderClause = 'h.id DESC';
    if (sortBy && allowedSorts[sortBy]) {
      orderClause = `${allowedSorts[sortBy]} ${sortOrder === 'asc' ? 'ASC' : 'DESC'}`;
    }

    // base query joins county to return county name
    let sql = `SELECT h.id, h.hos_name, h.hos_code, h.remark, h.county_id, c.county_name FROM atb_hospital h LEFT JOIN atb_county c ON h.county_id = c.id ORDER BY ${orderClause}`;

    if (page && limit) {
      sql += ' LIMIT ? OFFSET ?';
      const [rows] = await pool.query(sql, [limit, offset]);
      const [countRows] = await pool.query('SELECT COUNT(*) AS total FROM atb_hospital');
      const total = (countRows && countRows[0] && countRows[0].total) ? countRows[0].total : 0;
      return res.json({ hospitals: rows, total });
    } else {
      const [rows] = await pool.query(sql);
      return res.json({ hospitals: rows });
    }
  } catch (err) {
    console.error('Failed to fetch hospitals:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

// NOTE: previously this file exposed GET /counties which conflicted with routes/counties.js
// The counties list endpoint is provided by server/routes/counties.js. Removing the duplicate
// handler here to avoid route collision when both routers are mounted at '/api'.

// POST /api/hospitals
router.post('/hospitals', authMiddleware, async (req, res) => {
  try {
    const { hos_name, hos_code, remark, county_id } = req.body;
    if (!hos_name) return res.status(400).json({ message: 'hos_name required' });

    // ensure unique hos_name
    const [existing] = await pool.query('SELECT id FROM atb_hospital WHERE hos_name = ?', [hos_name]);
    if (existing && existing.length > 0) return res.status(409).json({ message: '医院名称已存在', field: 'hos_name' });

    const [result] = await pool.query('INSERT INTO atb_hospital (hos_name, hos_code, remark, county_id) VALUES (?, ?, ?, ?)', [hos_name, hos_code || null, remark || null, county_id || null]);
    const insertId = result.insertId;
    const [rows] = await pool.query('SELECT h.id, h.hos_name, h.hos_code, h.remark, h.county_id, c.county_name FROM atb_hospital h LEFT JOIN atb_county c ON h.county_id = c.id WHERE h.id = ?', [insertId]);

    // log creation
    createLog(req, { message: `新增医院 ${hos_name}`, tp: 'create', obj_json: JSON.stringify(rows[0] || { id: insertId, hos_name }) });

    res.status(201).json({ hospital: rows[0] });
  } catch (err) {
    console.error('Failed to create hospital:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

// PUT /api/hospitals/:id
router.put('/hospitals/:id', authMiddleware, async (req, res) => {
  try {
    const id = parseInt(req.params.id, 10);
    if (isNaN(id)) return res.status(400).json({ message: 'Invalid hospital id' });

    const { hos_name, hos_code, remark, county_id } = req.body;
    const fields = [];
    const params = [];

    if (typeof hos_name !== 'undefined') {
      // check uniqueness
      const [rows] = await pool.query('SELECT id FROM atb_hospital WHERE hos_name = ? AND id != ?', [hos_name, id]);
      if (rows && rows.length > 0) return res.status(409).json({ message: '医院名称已存在', field: 'hos_name' });
      fields.push('hos_name = ?'); params.push(hos_name);
    }
    if (typeof hos_code !== 'undefined') { fields.push('hos_code = ?'); params.push(hos_code); }
    if (typeof remark !== 'undefined') { fields.push('remark = ?'); params.push(remark); }
    if (typeof county_id !== 'undefined') { fields.push('county_id = ?'); params.push(county_id); }

    if (fields.length === 0) return res.status(400).json({ message: 'No fields to update' });

    params.push(id);
    const sql = `UPDATE atb_hospital SET ${fields.join(', ')} WHERE id = ?`;
    await pool.query(sql, params);

    const [updated] = await pool.query('SELECT h.id, h.hos_name, h.hos_code, h.remark, h.county_id, c.county_name FROM atb_hospital h LEFT JOIN atb_county c ON h.county_id = c.id WHERE h.id = ?', [id]);

    // log update
    createLog(req, { message: `编辑医院 id=${id}`, tp: 'update', obj_json: JSON.stringify(updated[0] || { id }) });

    res.json({ hospital: updated[0] });
  } catch (err) {
    console.error('Failed to update hospital:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

// DELETE /api/hospitals/:id
router.delete('/hospitals/:id', authMiddleware, async (req, res) => {
  try {
    const id = parseInt(req.params.id, 10);
    if (isNaN(id)) return res.status(400).json({ message: 'Invalid hospital id' });

    await pool.query('DELETE FROM atb_hospital WHERE id = ?', [id]);

    // log delete
    createLog(req, { message: `删除医院 id=${id}`, tp: 'delete', obj_json: JSON.stringify({ id }) });

    res.json({ ok: true });
  } catch (err) {
    console.error('Failed to delete hospital:', err);
    res.status(500).json({ message: 'Server error' });
  }
});

module.exports = router;
